import {
	fabric
} from "fabric";

import {
	parseGIF,
	decompressFrames
} from "./gifuct/gifuct-js";


export default class rwFabric {

	//new初始化，这个方法都会走
	constructor(id, opt) {
		this._id = id;
		this._canvas = null;
		this._actionType = 0; //0默认  1折线   2多边形
		this._lines = null;
	}


	/**初始化SVG
	 * @param {Object} opt
	 */
	initSVG(opt) {
		this._canvas = new fabric.Canvas(this._id, {
			backgroundVpt: opt.backgroundVpt | false, // 不受视口变换影响（也就是不管拖拽还是缩放画布，背景图都不受影响）
			isDrawingMode: opt.isDrawingMode | false, //设置是否可以绘制
			selectable: opt.selectable | false, //设置是否可以选中拖动  fabric提供的
			selection: opt.selection | false,
			interactive: opt.interactive | false, // 隐藏交互模式
			fireRightClick: opt.fireRightClick | false, // 启用右键，button的数字为3
			stopContextMenu: opt.stopContextMenu | false, // 禁止默认右键菜单
			centeredScaling: true, // 元素中心点缩放
			devicePixelRatio: true, // Retina 高清屏 屏幕支持
			selectionColor: 'transparent',
			selectionBorderColor: 'transparent',
			skipTargetFind: false // 禁止选中
		});
		// this._canvas.setDimensions({
		// 	width: window.innerWidth,
		// 	height: window.innerHeight
		// });
		this._canvas.renderOnAddRemove = true
	}


	/**设置背景图
	 * @param {Object} opt
	 */
	initSvgScene(opt) {
		var that = this
		fabric.Image.fromURL(opt.imgUrl, (oImg) => {
			oImg.set({
				// 通过scale来设置图片大小，这里设置和画布一样大
				scaleX: that._canvas.width / oImg.width,
				scaleY: that._canvas.height / oImg.height,
				// scaleX: 1,
				// scaleY: 1,
			});
			oImg.id = "-1" //默认为背景
			// 设置背景
			that._canvas.setBackgroundImage(oImg, that._canvas.renderAll.bind(that._canvas));
		});

	}
	/**设置背景色
	 * @param {Object} color
	 */
	initSvgSceneColer(color) {
		//this._canvas.backgroundColor = "#F7F7F7";
		this._canvas.backgroundColor = color;
	}
	/**设置操作
	 * @param {Object} type
	 */
	setActionType(type) {
		this._actionType = type;
		this._canvas.on('mouse:down', null)
	}
	/**
	 * 获取canavas对象
	 */
	getCanvas() {
		return this._canvas
	}
	/**
	 * 获取所有对象
	 */
	getObjects() {
		return this._canvas.getObjects()
	}
	/**查找对象
	 * @param {Object} id
	 */
	getObjectById(id) {
		var that = this
		that._canvas.getObjects().forEach(function(o) {
			if (o.id === id) {
				return o;
			}
		})
		return null;
	}
	/**
	 * 设置活动对象
	 */
	setActiveObject(o) {
		this._canvas.setActiveObject(o)
		this.renderAll()
		// this._canvas.discardActiveObject();
	}

	renderAll() {
		this._canvas.renderAll();
	}

	//刷新
	requestRender() {
		var that = this;
		render()

		function render() {
			if (that._canvas) {
				that._canvas.renderAll();
			}
			fabric.util.requestAnimFrame(render);
		}
	}

	removeAll(){
		var that = this
		that._canvas.getObjects().forEach(function(o) {

			that._canvas.remove(o)

		})
	}

	remove(o) {
		this._canvas.remove(o)
	}

	removeById(id) {
		var that = this
		that._canvas.getObjects().forEach(function(o) {
			if (o.id === id) {
				that._canvas.remove(o)
			}
		})
	}

//静止操作对象
	lockObject(obj){
		obj.hasBorders = false //不显示选中时的边
		obj.hasControls = false //不显示选中时的9个方块
		//静止移动
		obj.lockMovementX = true
		obj.lockMovementY = true
	}


	// =======================创建对象=====================================//
	/**
	 * @param {Object} opt
	 */
	createSvgText(opt) {
		var text = new fabric.Text(opt.text, {
			id: opt.id,
			left: opt.left,
			top: opt.top
		});
		text.set({
			transparentCorners: false,
			cornerColor: 'blue',
			cornerStrokeColor: 'red',
			borderColor: 'red',
			cornerSize: 12,
			padding: 10,
			cornerStyle: 'circle',
			borderDashArray: [3, 3]
		});

		this._canvas.add(text);

	}


	/**
	 * @param {Object} opt
	 */
	createSvgImgAndText(opt) {
		var that = this
		// let result = [];
		fabric.Image.fromURL(opt.imgUrl, oImg => {
			oImg.scale(1).set({
				left: opt.imgLeft,
				top: opt.imgTop,
				width: opt.imgWidth,
				height: opt.imgHeight,
				angle: opt.imgAngle, //旋转角度
				selectable:opt.selectable,

			});

			const text = new fabric.Text(opt.text, {
				fontSize: opt.textFontSize,
				top: opt.textTop,
				left: opt.textLeft,
				angle: opt.textAngle, //旋转角度

			})
			text.set({
				fill: 'white'
			})

			let group = new fabric.Group([oImg, text])
			group.id = opt.id
			group.channelTypeCode = opt.channelTypeCode
			group.channelId = opt.channelId
			group.objType = opt.objType
			group.channelCode = opt.channelCode
			group.text = opt.text
			group.iconGroupId = opt.iconGroupId
			group.spaceId = opt.spaceId
			group.spaceName=opt.spaceName
			group.set({

				transparentCorners: false,
				cornerColor: 'blue',
				cornerStrokeColor: 'red',
				borderColor: 'red',
				cornerSize: 12,
				padding: 10,
				cornerStyle: 'circle',
				borderDashArray: [3, 3],

			});

			that._canvas.add(group)
		})

	}



	/**
	 * @param {Object} opt
	 */
	createSvgImg(opt) {
		var that = this
		fabric.Image.fromURL(opt.imgUrl, oImg => {
			oImg.scale(1).set({
				left: opt.left,
				top: opt.top,
				width: opt.width,
				height: opt.height,
				angle: opt.angle, //旋转角度
				// 这里可以通过scaleX和scaleY来设置图片绘制后的大小，这里为原来大小的一半
				scaleX: opt.scaleX,
				scaleY: opt.scaleY,
				selectable:false,
			});
			oImg.id = opt.id
			oImg.channelTypeCode = opt.channelTypeCode
			oImg.channelId = opt.channelId
			oImg.objType = opt.objType
			oImg.channelCode = opt.channelCode
			oImg.text = opt.text
			oImg.iconGroupId = opt.iconGroupId
			oImg.selectable=false
			oImg.set({
				selectable:false,
				transparentCorners: false,
				cornerColor: 'blue',
				cornerStrokeColor: 'red',
				borderColor: 'red',
				cornerSize: 12,
				padding: 10,
				cornerStyle: 'circle',
				borderDashArray: [3, 3],

			});
			that.lockObject(oImg)
			that._canvas.add(oImg)
		})
	}



	createSvgFile(opt) {
		var that = this;
		fabric.loadSVGFromURL(opt.svgFile, function(objects, options) {
			var drink = fabric.util.groupSVGElements(objects, options);
			drink.set({
				left: opt.left,
				top: opt.top,
				width: opt.width,
				height: opt.height,
				angle: opt.angle, //旋转角度
				// 这里可以通过scaleX和scaleY来设置图片绘制后的大小，这里为原来大小的一半
				scaleX: opt.scaleX,
				scaleY: opt.scaleY,
			});
			drink.set({
				transparentCorners: false,
				cornerColor: 'blue',
				cornerStrokeColor: 'red',
				borderColor: 'red',
				cornerSize: 12,
				padding: 10,
				cornerStyle: 'circle',
				borderDashArray: [3, 3]
			});

			that._canvas.add(drink);
			// that._canvas.calcOffset();
			// that._canvas.renderAll();
		});
	}


	/**
	 * @param {Object} opt
	 */
	createImg(opt) {
		var that = this
		fabric.Image.fromURL(opt.imgUrl, oImg => {
			oImg.scale(1).set({
				left: opt.left,
				top: opt.top,
				width: opt.width,
				height: opt.height,
				angle: opt.angle, //旋转角度
				// 这里可以通过scaleX和scaleY来设置图片绘制后的大小，这里为原来大小的一半
				scaleX: opt.scaleX,
				scaleY: opt.scaleY,

			});
			oImg.id = opt.id
			oImg.channelTypeCode = opt.channelTypeCode
			oImg.channelId = opt.channelId
			oImg.objType = opt.objType
			oImg.channelCode = opt.channelCode
			oImg.text = opt.text
			oImg.set({
				transparentCorners: false,
				cornerColor: 'blue',
				cornerStrokeColor: 'red',
				borderColor: 'red',
				cornerSize: 12,
				padding: 10,
				cornerStyle: 'circle',
				borderDashArray: [3, 3]
			});

			that._canvas.add(oImg)
		})
	}

	createGif(opt) {
		var that = this;
		var url = opt.imgUrl;
		var drink = fabric.Image.fromURL(url, function(img) {
			img.width = opt.width;
			img.height = opt.height;
			img.left = opt.left;
			img.top = opt.top;
			img.scaleX = opt.scaleX;
			img.scaleY = opt.scaleY;
			img.id = opt.id;
			img.zindex = opt.zindex; //目前参数无效
			img.set({
				transparentCorners: false,
				cornerColor: 'blue',
				cornerStrokeColor: 'red',
				borderColor: 'red',
				cornerSize: 12,
				padding: 10,
				cornerStyle: 'circle',
				borderDashArray: [3, 3]
			});

			gif(url, function(frames, delay) {
				var framesIndex = 0,
					animInterval;
				img.dirty = true;
				img._render = function(ctx) {
					ctx.drawImage(frames[framesIndex], -this.width / 2, -this.height / 2, this
						.width, this.height);
				}
				img.play = function() {
					if (typeof(animInterval) === 'undefined') {
						animInterval = setInterval(function() {
							framesIndex++;
							if (framesIndex === frames.length) {
								framesIndex = 0;
							}
						}, delay);
					}
				}
				img.stop = function() {
					clearInterval(animInterval);
					animInterval = undefined;
				}
				img.play();
				that._canvas.add(img);
			})
		})


		function gif(url, callback) {
			var tempCanvas = document.createElement('canvas');
			var tempCtx = tempCanvas.getContext('2d');
			var gifCanvas = document.createElement('canvas');
			var gifCtx = gifCanvas.getContext('2d');
			var imgs = [];
			var xhr = new XMLHttpRequest();
			xhr.open('get', url, true);
			xhr.responseType = 'arraybuffer';
			xhr.onload = function() {
				var tempBitmap = {};
				tempBitmap.url = url;
				var arrayBuffer = xhr.response;
				if (arrayBuffer) {
					var gif = new GIF(arrayBuffer);
					var frames = gif.decompressFrames(true);
					gifCanvas.width = frames[0].dims.width;
					gifCanvas.height = frames[0].dims.height;

					for (var i = 0; i < frames.length; i++) {
						createFrame(frames[i]);
					}
					callback(imgs, frames[0].delay);
				}

			}
			xhr.send(null);
			var disposalType;

			function createFrame(frame) {
				if (!disposalType) {
					disposalType = frame.disposalType;
				}
				var dims = frame.dims;
				tempCanvas.width = dims.width;
				tempCanvas.height = dims.height;
				var frameImageData = tempCtx.createImageData(dims.width, dims.height);
				frameImageData.data.set(frame.patch);
				if (disposalType !== 1) {
					gifCtx.clearRect(0, 0, gifCanvas.width, gifCanvas.height);
				}
				tempCtx.putImageData(frameImageData, 0, 0);
				gifCtx.drawImage(tempCanvas, dims.left, dims.top);
				var dataURL = gifCanvas.toDataURL('image/png');
				var tempImg = fabric.util.createImage();
				tempImg.src = dataURL;
				imgs.push(tempImg);
			}
		}

	}

	createRect(obj){
		var that = this
		console.log(obj);
		//据文字个数设置方图宽度
		if(obj.kpi.length!=0){
			obj.rectWidth=(obj.text.length+obj.kpi.length)*28;
		}else{
			obj.rectWidth=obj.text.length*28;
		}
		//绘制方图
		var rect = new fabric.Rect({
			fill:'red',
			width:obj.rectWidth,
			height:obj.rectHeight,
			originX: 'center', //调整中心点的X轴坐标
			originY: 'center' ,//调整中心点的Y轴坐标
			stroke: '#000' // 边框颜色
		});
		//绘制文本
		var text = new fabric.Text(obj.text+":"+obj.kpi, {
			fontSize: 20,
			originX: 'center',
			originY: 'center'
		})
		//进行组合
		let group = new fabric.Group([rect, text], {
			id:obj.groupId,
			left:obj.groupLeft,
			top: obj.gorupTop,
			angle: obj.groupAngle
		})

		that._canvas.add(group);
	}


	// =======================创建对象=====================================//


	// =======================创建事件=====================================//
	/**拖东事件
	 */
	initMoveEvent(func) {
		var that = this
		that._canvas.on('object:moving', function(event) {
			var id;
			if (event.target) {
				id = event.target.id
			}
			if (id) {
				that._canvas.getObjects().forEach(function(o) {
					if (o.id === id) {
						if (typeof(func) == 'function') {
							func(o)
						}
					}
				})
			} else {
				func("点击空白位置", false)
			}
		});
	}
	/**
	 * 左键up事件
	 */
	initUpEvent(func) {
		var that = this
		that._canvas.on('mouse:up', function(event) {
			var id;
			if (event.target) {
				id = event.target.id
			}
			if (id) {
				that._canvas.getObjects().forEach(function(o) {
					if (o.id === id) {
						if (typeof(func) == 'function') {
							func(o, true)
						}
					}
				})
			} else {
				func("点击空白位置", false)
			}
		});
	}
	/**
	 * 左键down事件
	 */
	initDownEvent(func) {
		var that = this
		that._canvas.on('mouse:down', function(event) {
			func(event.target)
		});
	}
	/**旋转事件
	 */
	initRotatingEvent(func) {
		var that = this
		that._canvas.on("object:rotating", function(event) {
			console.log("selection:rotating   " + event.target)
			if (typeof(func) == 'function') {
				func(event.target)
			}
		});
	}

	/**缩放事件
	 */
	initScalingEvent(func) {
		var that = this
		that._canvas.on("object:scaling", function(event) {
			console.log("selection:scaling   " + event.target)
			if (typeof(func) == 'function') {
				func(event.target)
			}
		});
	}




	/**静止移动
	 */
	setNotMove() {
		var that = this
		that._canvas.on("selection:created", function(event) {
			that._canvas.discardActiveObject();
			that._canvas.requestRenderAll();
		});
	}


	/**双击
	 * @param {Object} func
	 */
	initDblclickEvent(func) {
		var that = this
		that._canvas.on('mouse:dblclick', function(e) {
			if (typeof(func) == 'function') {
				func(e.target)
			}
		})
	}


	/**右击
	 * @param {Object} func
	 */
	initRightClickEvent(func) {
		window.oncontextmenu = function(e) {
			e.preventDefault()
		}

		var that = this
		that._canvas.on('mouse:down', function(e) {
			if (e.button != 3) {
				return
			}
			if (!e.target) {
				return
			}
			if (typeof(func) == 'function') {
				func(e.target)
			}
		})

	}


	/**移出
	 * @param {Object} func
	 */
	initOutEvent(func) {
		var that = this
		that._canvas.on('mouse:out', function(e) {
			if (typeof(func) == 'function') {
				func(e.target)
			}
		})


	}

	/**移入
	 * @param {Object} func
	 */
	initOverEvent(func) {
		var that = this
		that._canvas.on('mouse:over', function(e) {
			if (typeof(func) == 'function') {
				func(e)
				let str = ''
				if(e.target.objType === '4'){
					str = e.target.spaceName
				}
				// 创建或更新信息窗口的内容和位置
				var infoWindow = new fabric.Textbox(str, {
					left: e.e.clientX ,
					top: e.e.clientY ,
					fontSize: 18,
					fill: '#1e2f2f',
					backgroundColor:  'rgba(190,190,190,0.5)',
					padding: 0,
					hasControls: false,
					hasBorders: false,
					selectable: false,
				});
				// 将信息窗口添加到画布上以模拟信息窗口效果
				that._canvas.add(infoWindow);
				// 在 mouse:out 事件中移除信息窗口
				that._canvas.on('mouse:out', function(outEvent) {
					that._canvas.remove(infoWindow);
				});
			}
		})
	}

	/**画布移动
	 * @param {Object} func
	 */
	initSceneMoveEvent(func) {
		var that = this
		//鼠标按下事件
		that._canvas.on("mouse:down", function(e) {
			this.panning = true;
			that._canvas.selection = false;
		});
		//鼠标抬起事件
		that._canvas.on("mouse:up", function(e) {
			this.panning = false;
			that._canvas.selection = true;
		});
		// 画布移动事件
		that._canvas.on("mouse:move", function(e) {
			if (this.panning && e && e.e) {
				var delta = new fabric.Point(e.e.movementX, e.e.movementY);
				that._canvas.relativePan(delta);
				if (typeof(func) == 'function') {
					func(delta)
				}
			}
		});
	}
	/**画布缩放
	 * @param {Object} func
	 */
	initZoomEvent(func) {
		var that = this
		// 鼠标滚动画布放大缩小
		that._canvas.on("mouse:wheel", function(e) {
			var zoom = (event.deltaY > 0 ? -0.1 : 0.1) + that._canvas.getZoom();
			zoom = Math.max(0.1, zoom); //最小为原来的1/10
			zoom = Math.min(3, zoom); //最大是原来的3倍
			var zoomPoint = new fabric.Point(event.pageX, event.pageY);
			that._canvas.zoomToPoint(zoomPoint, zoom);
			if (typeof(func) == 'function') {
				func(zoom)
			}
		});
	}
	// =======================创建事件=====================================//






	// =======================折线、多边形=====================================//
	// 创建折线
	createPolyline(e) {
		const currentPoint = e.absolutePointer
		this._lines = new fabric.Polyline(
			[{
				x: currentPoint.x,
				y: currentPoint.y
			},
				{
					x: currentPoint.x,
					y: currentPoint.y
				}
			], {
				fill: 'transparent',
				stroke: 'red',
				strokeWidth: 10,
				// strokeDashArray: [8, 4],
				objectCaching: false,

			}
		)
		this._canvas.add(this._lines)
	}

	// 修改当前正在创建的折线
	changeCurrentPolyline(e) {
		const currentPoint = e.absolutePointer
		let points = this._lines.points
		points.push({
			x: currentPoint.x,
			y: currentPoint.y
		})
		this._canvas.requestRenderAll()
	}

	// 折线橡皮带
	changePolylineBelt(e) {
		const currentPoint = e.absolutePointer
		let points = this._lines.points
		points[points.length - 1].x = currentPoint.x
		points[points.length - 1].y = currentPoint.y
		this._canvas.requestRenderAll()
	}

	// 完成折线绘制
	finishPolyline(e) {
		var that = this;
		const currentPoint = e.absolutePointer
		let points = that._lines.points
		points[points.length - 1].x = currentPoint.x
		points[points.length - 1].y = currentPoint.y
		points.pop()
		points.pop()
		// 按需添加自闭合代码
		if (that._actionType == 2) {
			if (points[0].x != points[points.length - 1].x && points[0].y != points[points.length - 1].y) {
				that.changeCurrentPolyline({
					absolutePointer: {
						x: points[0].x,
						y: points[0].y
					}
				})
			}
		}

		that._canvas.remove(that._lines)
		if (points.length > 1) {
			let polyline = new fabric.Polyline(points, {
				stroke: 'red',
				fill: 'transparent'
			})
			that._canvas.add(polyline)
		}
		that._lines = null
		that._canvas.requestRenderAll()
	}

	// 画多边形
	currentPolyline() {
		var that = this;
		that._canvas.on('mouse:down', function(e) {
			if (!(that._actionType == 1 || that._actionType == 2)) {
				return
			}
			if (that._lines === null) {
				that.createPolyline(e)
			} else {
				that.changeCurrentPolyline(e)
			}
		}) // 鼠标在画布上按下
		that._canvas.on('mouse:move', function(e) {
			if (!(that._actionType == 1 || that._actionType == 2)) {
				return
			}
			if (that._lines) {
				that.changePolylineBelt(e)
			}
		}) // 鼠标在画布上移动
		that._canvas.on('mouse:dblclick', function(e) {
			if (!(that._actionType == 1 || that._actionType == 2)) {
				return
			}
			that.finishPolyline(e)
		}) // 鼠标在画布上双击
	}

	// =======================折线=====================================//



}